package cn.machen.www.fashion.utils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 请求路径：/xxServlet?method=xxx
 * 功能：动态执行请求路径中的method方法
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //通过反射动态执行method方法
        String methodName = request.getParameter("method");
        Method method = null;
        try {
            //得到本类对象的名为methodName的方法
            method = getClass().getMethod(methodName, new Class[]{HttpServletRequest.class, HttpServletResponse.class});
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("调用的方法"+methodName+"不存在！");
        }
        //执行方法
        try {
                //返回跳转的路径
            String result = (String)method.invoke(this, new Object[]{request, response});
            if((result!=null) && (!result.trim().isEmpty())){
                int index = result.indexOf(":");
                if(index == -1){   //默认执行转发功能
                    request.getRequestDispatcher(result).forward(request,response);
                }else{
                    String start = result.substring(0,index);
                    String path = result.substring(index+1);
                    if("f".equals(start)){
                        request.getRequestDispatcher(path).forward(request,response);
                    }else if("r".equals(start)){
                        response.sendRedirect(request.getContextPath()+path);
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
           throw new RuntimeException(e);
        }

    }
}
